package com.example.meet.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.framework.base.BaseBackActivity;
import com.example.framework.bmob.User;
import com.example.framework.bmob.bmobManager.BmobManager;
import com.example.framework.utils.CommonUtils;
import com.example.meet.R;
import com.example.meet.adapter.AddFriendAdapter;
import com.example.meet.model.AddFriendModel;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 * 添加好友的UI
 */
public class AddFriendActivity extends BaseBackActivity implements View.OnClickListener{

    /**
     * 1. 模拟一个用户数据
     * 2. 根据条件查询
     * 3. 推荐好友
     */

    private LinearLayout ll_to_contact;
    private EditText et_phone;
    private ImageView iv_search;
    private RecyclerView mSearchResult;
    private View include_empty_view;

    private AddFriendAdapter adapter;
    private List<AddFriendModel> mData = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_friend);
        initView();
    }

    private void initView() {
        ll_to_contact = (LinearLayout) findViewById(R.id.ll_to_contact);
        et_phone = (EditText) findViewById(R.id.et_phone);
        iv_search = (ImageView) findViewById(R.id.iv_search);
        mSearchResult = (RecyclerView) findViewById(R.id.mSearchResult);
        include_empty_view = findViewById(R.id.include_empty_view);

        ll_to_contact.setOnClickListener(this);
        iv_search.setOnClickListener(this);

        // 列表的实现
        // 添加一个布局，线性布局
        mSearchResult.setLayoutManager(new LinearLayoutManager(this));
        // 为每一个list添加一个下划线
        mSearchResult.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        adapter = new AddFriendAdapter(this, mData);
        mSearchResult.setAdapter(adapter);

        adapter.setOnClickListener(new AddFriendAdapter.OnClickListener() {
            @Override
            public void onClick(int position) {
                Toast.makeText(AddFriendActivity.this, "position" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_to_contact:

                break;

            case R.id.iv_search:
                // 通过电话号码查询
                queryUserFromPhone();
                break;
        }
    }

    /**
     * 通过电话号码查询一个用户
     * tokenPhoto='http://b-ssl.duitang.com/uploads/item/201409/30/20140930134136_wk4Jz.jpeg'
     * tokenNickName='神经一样的妞'
     * nickName='神经一样的妞'
     * photo='http://b-ssl.duitang.com/uploads/item/201409/30/20140930134136_wk4Jz.jpeg'
     * sex=false
     * desc='好不好啊，真是一个温柔的词，像在摸着你的小脑袋。'
     * age=29
     * birthday='1992-9-21'
     * constellation='金牛座'
     * hobby='音乐'
     * status='单身'
     */
    private void queryUserFromPhone() {
        // 1. 获取电话号码
        String phone = et_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "手机号码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 2. 过滤自己
        String myPhone = BmobManager.getInstance().getUser().getMobilePhoneNumber();
        if (myPhone.equals(phone)) {
            Toast.makeText(this, "不能查询本人", Toast.LENGTH_SHORT).show();
            return;
        }

        // 3. 查询
        BmobManager.getInstance().queryFriendFromPhone(phone, new FindListener<User>() {
            @Override
            public void done(List<User> list, BmobException e) {
                if (e != null) {
                    return;
                }
                if (!CommonUtils.isEmpty(list)) {
                    User user = list.get(0);
                    include_empty_view.setVisibility(View.GONE);
                    mSearchResult.setVisibility(View.VISIBLE);

                    // 每次查询有数据就清空
                    mData.clear();

                    // 查询结果
                    addTitle("查询结果");
                    addContent(user);
                    adapter.notifyDataSetChanged();
                    // 推荐好友
                    pushUser();

                } else {
                    // 显示空数据
                    include_empty_view.setVisibility(View.VISIBLE);
                    mSearchResult.setVisibility(View.GONE);
                }
            }
        });
    }

    /**
     * 推荐好友
     */
    private void pushUser() {
        // 查询所有的好友，取100个
        BmobManager.getInstance().queryAllUser(new FindListener<User>() {
            @Override
            public void done(List<User> list, BmobException e) {
                if (e == null) {
                    if (!CommonUtils.isEmpty(list)) {
                        addTitle("推荐好友");
                        int total = list.size();
                        if (total > 20) {
                            int index = (int) ((Math.random() * total) + 1) - 20;
                            for (int i = index; i < index + 20; i++) {
                                // 不推荐自己
                                String myPhone = BmobManager.getInstance().getUser().getMobilePhoneNumber();
                                if (list.get(i).getMobilePhoneNumber().equals(myPhone)) {
                                    continue;
                                }
                                addContent(list.get(i));
                            }
                        } else {
                            for (int i = 0; i < total; i++) {
                                String myPhone = BmobManager.getInstance().getUser().getMobilePhoneNumber();
                                if (list.get(i).getMobilePhoneNumber().equals(myPhone)) {
                                    continue;
                                }
                                addContent(list.get(i));
                            }
                        }

                        adapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    /**
     * 添加标题
     * 不在addTitle和addContent添加刷新，是因为在推荐好友这个地方，一下子添加20个，会刷新20次，性能太差
     *
     * @param title
     */
    private void addTitle(String title) {
        AddFriendModel model = new AddFriendModel();
        model.setType(AddFriendAdapter.TYPE_TITLE);
        model.setTitle(title);
        mData.add(model);
    }

    /**
     * 添加内容
     * @param user
     */
    private void addContent(User user) {
        AddFriendModel model = new AddFriendModel();
        model.setType(AddFriendAdapter.TYPE_CONTENT);
        model.setUserId(user.getObjectId());
        model.setPhoto(user.getPhoto());
        model.setSex(user.isSex());
        model.setAge(user.getAge());
        model.setNickname(user.getNickName());
        model.setDesc(user.getDesc());
        mData.add(model);
    }
}